#include "repo_res_material.h"
#include "debug/logger.h"
#include "fileio/fileio.h"
#include "misc/strutil.h"

namespace renderit
{
	namespace messiah
	{
		void repo_res_material::load()
		{
			is_dirty_ = false;
			std::string path = fileio::join(dir_, "resource.xml");
			if (!fileio::exists(path))
			{
				logger::warn("Load Material(%s) Failed, Missing File!", path.c_str());
				return;
			}

			doc_.LoadFile(path.c_str());

			std::vector<guid_info> r;
			find_guid_in_path(doc_.RootElement(), "Resource", r);
			for (auto& gi : r)
			{
				xml_guid_map_[gi.guid].push_back(gi);
			}
		}

		void repo_res_material::save()
		{
			if (!is_dirty_)
			{
				return;
			}
			is_dirty_ = false;
			std::string path = fileio::join(dir_, "resource.xml");
			tinyxml2::XMLError err = doc_.SaveFile(path.c_str());
			if (err != tinyxml2::XML_NO_ERROR)
			{
				logger::warn("Save Material Error:%d", err);
			}
		}

		uint32 repo_res_material::replace_guid(const std::string& from_guid, const std::string& to_guid)
		{
			if (!strutil::str_is_guid(from_guid) || !strutil::str_is_guid(to_guid))
			{
				logger::warn("Material replace guid Check Failed(%s, %s)", from_guid.c_str(), to_guid.c_str());
				return 0;
			}

			auto& array = xml_guid_map_[from_guid];
			for (auto& gi : array)
			{
				is_dirty_ = true;
				gi.xml_elem_->SetText(to_guid.c_str());
			}
			return array.size();
		}

		std::vector<std::string> repo_res_material::get_deps()
		{
			std::vector<std::string> r;
			for (auto& it : xml_guid_map_)
			{
				r.push_back(it.first);
			}
			return std::move(r);
		}
	}
}